package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"time"
)

func handleConn(conn net.Conn) {
	defer conn.Close()

	//创建一个10秒的超时定时器
	timeout := time.NewTimer(10 * time.Second)
	defer timeout.Stop()

	//创建一个通道用于接收客户端发送的数据
	messages := make(chan string, 1)

	go func() {
		input := bufio.NewScanner(conn)
		for input.Scan() {
			messages <- input.Text()
		}
		close(messages)
	}()

	for {
		select {
		case msg, ok := <-messages:
			if !ok {
				return
			}
			fmt.Fprintln(conn, "Echo:", msg)

			//重置超时定时器
			if !timeout.Stop() {
				<-timeout.C
			}
			timeout.Reset(10 * time.Second)

		case <-timeout.C:
			//超时断开连接
			fmt.Fprintln(conn, "Connection timed out due to inactivity")
			return
		}
	}
}

func main() {
	listener, err := net.Listen("tcp", "127.0.0.1:8080")
	if err != nil {
		log.Fatal(err)
	}

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Print(err)
			continue
		}
		go handleConn(conn)
	}
}
